package org.dromara.chicken.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.AuditDto;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.erp.domain.ErpGoodsInOutInfo;
import org.dromara.erp.domain.ErpProducts;
import org.dromara.erp.mapper.ErpGoodsInOutInfoMapper;
import org.dromara.erp.mapper.ErpProductsMapper;
import org.dromara.chicken.domain.Grow;
import org.dromara.chicken.domain.GrowInfo;
import org.dromara.chicken.mapper.GrowInfoMapper;
import org.dromara.chicken.mapper.GrowMapper;
import org.dromara.chicken.service.IGrowService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 成长记录Service业务层处理
 *
 * @author Mr Lei QQ:235921049
 * @date 2024-06-14
 */
@RequiredArgsConstructor
@Service
public class GrowServiceImpl implements IGrowService {

    private final GrowMapper baseMapper;
    private final GrowInfoMapper infoMapper;
    private final ErpProductsMapper productsMapper;
    private final ErpGoodsInOutInfoMapper goodsInOutInfoMapper;

    /**
     * 查询成长记录
     */
    @Override
    public Grow queryById(Long id){
        //查询主表
        Grow grow = baseMapper.selectById(id);
        //根据主表查询子表
        LambdaQueryWrapper<GrowInfo> infoWrapper = new LambdaQueryWrapper<>();
        infoWrapper.eq(GrowInfo::getOrderId,id);
        List<GrowInfo> infos = infoMapper.selectList(infoWrapper);
        grow.setContentInfo(infos);
        return grow;
    }

    /**
     * 查询成长记录列表
     */
    @Override
    public TableDataInfo<Grow> queryPageList(Grow bo, PageQuery pageQuery) {
        Page<Grow> result = baseMapper.queryPageList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询成长记录列表
     */
    @Override
    public List<Grow> queryList(Grow bo) {
        LambdaQueryWrapper<Grow> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Grow> buildQueryWrapper(Grow bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Grow> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), Grow::getOrderNo, bo.getOrderNo());
        lqw.eq(StringUtils.isNotBlank(bo.getTreatId()), Grow::getTreatId, bo.getTreatId());
        lqw.eq(StringUtils.isNotBlank(bo.getHatchId()), Grow::getHatchId, bo.getHatchId());
        lqw.eq(bo.getHappenTime() != null, Grow::getHappenTime, bo.getHappenTime());
        lqw.eq(bo.getAuditStatus() != null, Grow::getAuditStatus, bo.getAuditStatus());
        lqw.eq(bo.getAuditTime() != null, Grow::getAuditTime, bo.getAuditTime());
        return lqw;
    }

    /**
     * 新增成长记录
     */
    @Override
    public Boolean insertByBo(Grow bo) {
        validEntityBeforeSave(bo);
        //执行主表新增
        boolean flag = baseMapper.insert(bo) > 0;
        if (flag) {
            //主表返回新增的ID
            bo.setId(bo.getId());
            //获取子表列表数据
            List<GrowInfo> info = bo.getContentInfo();
            info.forEach(x->{
                //设置子表关联ID
                x.setOrderId(bo.getId());
                //执行子表新增方法
                infoMapper.insert(x);
            });
        }
        return flag;
    }

    /**
     * 修改成长记录
     */
    @Override
    public Boolean updateByBo(Grow bo) {
        validEntityBeforeSave(bo);
        List<GrowInfo> info = bo.getContentInfo();
        info.forEach(x->{
            x.setOrderId(bo.getId());
            if (x.getId() == null) {
                //如果有新增子表，则调用新增的方法
                infoMapper.insert(x);
            }
            //其他原有的则执行编辑
            infoMapper.updateById(x);
        });

        return baseMapper.updateById(bo) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Grow entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除成长记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验

        }
        //删除主表的同时删除子表
        LambdaQueryWrapper<GrowInfo> infoWrapper = new LambdaQueryWrapper<>();
        //主表用id则用wrapper.eq，主表是ids则用wrapper.in
        infoWrapper.in(GrowInfo::getOrderId,ids);
        //执行删除子表的方法
        infoMapper.delete(infoWrapper);
        //执行删除主表的方法
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /*生成默认标题*/
    @Override
    public String defaultTitle(String formatDate) {
        Integer totalNum = baseMapper.selectByDateCunt(formatDate);
        //最低3位数，不足前面用0填充
        String format = String.format("%03d", totalNum);
        //拼接成新的标题
        return format;
    }

    /*审核操作*/
    @Override
    public void updateAudit(AuditDto dto) {
        LambdaUpdateWrapper<Grow> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Grow::getId, dto.getId());//设置更新条件
        updateWrapper.set(Grow::getAuditStatus, dto.getAuditStatus());//设置更新字段
        updateWrapper.set(Grow::getAuditRemark, dto.getAuditRemark());//设置更新字段
        updateWrapper.set(Grow::getAuditTime, new Date());//设置时间
        //根据审核表的id去查询主表明细
        Grow grow = baseMapper.selectById(dto.getId());
        //如果审核通过或单据作废执行
        if(dto.getAuditStatus() == 2 || dto.getAuditStatus() == 4){
            //如果单据已审核，则无法再次审核
            if(dto.getAuditStatus().equals(grow.getAuditStatus())){
                //抛出异常
                throw new RuntimeException("单据已审核，不能再进行同样的操作");
            }
            //根据order_id查询ChickenFeedOutInfo表
            LambdaQueryWrapper<GrowInfo> infoWrapper = new LambdaQueryWrapper<>();
            infoWrapper.eq(GrowInfo::getOrderId,dto.getId());
            List<GrowInfo> infos = infoMapper.selectList(infoWrapper);
            //TODO 这里应该做库存大于0的校验
            infos.forEach(o->{
                //查询erp_products表
                ErpProducts goods = productsMapper.findById(o.getProductId());
                //根据info列表遍历出来后，更新erp_products表的stock字段
                ErpProducts product = new ErpProducts();
                //把主表的order名称和模块名设置到erp_goods_in_out_info表的相关字段
                ErpGoodsInOutInfo goodsInfo = new ErpGoodsInOutInfo();
                //审核通过执行-减库存
                if(dto.getAuditStatus() == 2){
                    product.setStock(goods.getStock().subtract(o.getDrugNum()));
                    //设置说明
                    goodsInfo.setRemark(grow.getRemark());
                }else{
                    //作废执行-加库存
                    product.setStock(goods.getStock().add(o.getDrugNum()));
                    goodsInfo.setRemark("单据作废");
                }
                //设置更新商品的ID
                product.setId(o.getProductId());
                //执行erp_products的更新方法
                productsMapper.updateById(product);
                //设置商品ID
                goodsInfo.setGoodsId(o.getProductId());
                //设置模块名称
                goodsInfo.setModuleName("鸡场治疗");
                //设置订单名称
                goodsInfo.setOrderName(grow.getOrderNo());
                //设置分类
                goodsInfo.setCateId(o.getProductsCateId());
                //TODO 设置规格,这里出库是以商品基本包装单位为准，所以不需要做多计量计算
                goodsInfo.setGoodsSpecId(goods.getUnitId());
                //变更后的新库存
                goodsInfo.setStock(product.getStock());
                //设置数量
                goodsInfo.setAmount(o.getDrugNum());
                //设置单价
                goodsInfo.setPrice(o.getPrice());
                //设置金额
                goodsInfo.setMoney(o.getMoney());
                //执行erp_goods_in_out_info添加方法
                goodsInOutInfoMapper.insert(goodsInfo);
            });
        }
        //执行主表的更新方法
        baseMapper.update(updateWrapper);
    }
}
